class HttpManager {
	public constructor() {
	}

	private static _instance:HttpManager;
	public static instance():HttpManager{
		if(!HttpManager._instance){
			HttpManager._instance = new HttpManager();
		}
		return HttpManager._instance;
	}

	private _http:egret.HttpRequest;
	private _token:string;
	private _callList:Dictionary<any>;

	public get token(){
		return this._token;
	}

	public init(){
		if(!this._http){
			this._http = new egret.HttpRequest();
			this._http.responseType = egret.HttpResponseType.TEXT;
			this.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			this._http.addEventListener(egret.Event.COMPLETE,this.onCompleteHandler,this);
			this._http.addEventListener(egret.IOErrorEvent.IO_ERROR,this.onIOErrorHandler,this);
			this._http.addEventListener(egret.ProgressEvent.PROGRESS,this.onProgressHandler,this);
		}
	}

	private onCompleteHandler(e:egret.Event){
		let req = <egret.HttpRequest>e.currentTarget;
		let response:string = req.response;
		
		if(response){
			let json = JSON.parse(response);
			if(json['code']){
				if(json['code'] == 205)
				{
					MessageUtil.error(json['message']);
					return;
				}
				if(json['code'] != 200){
					//登录时会有一个code， 200表示登录成功
					return;
				}
			}

			//缓存token
			let token = json['token'];
		}

		//执行回调列表中的函数
		if(this._callList){
			let key = req['_url'];
			let value = this._callList.getValueByKey(key);
			if(value && value.call){
				value.call.call(value.scope, response);
			}
			this.removeResponseCall(key);
		}
	}

	private onIOErrorHandler(e:egret.Event){
		var req = <egret.HttpRequest>e.currentTarget;
	}

	private onProgressHandler(e:egret.Event){
		var req = <egret.HttpRequest>e.currentTarget;
	}

	/**
	 * 设置HTTP请求头
	 */
	public setRequestHeader(header:string, value:string){
		if(this._http){
			this._http.setRequestHeader(header, value);
		}
	}

	/**
	 * GET请求
	 */
	public sendGet(url:string){
		this._http.open(url,egret.HttpMethod.GET);
		this._http.send();
	}

	/**
	 * POST请求
	 */
	public sendPost(url:string, data?:any, call?:Function, scope?:any){
		// if(LoginManager.instance().isAccredit){
			LogUtil.log('postData:' + data);
			this._http.open(url,egret.HttpMethod.POST);
			this._http.send(data);
			this.addResponseCall(url, {call:call, scope:call});
		// }
	}

	/**
	 * 添加回调
	 */
	public addResponseCall(key:string, value:any){
		if(!this._callList){
			this._callList = new Dictionary<any>();
		}
		this._callList.add(key, value)
	}

	/**
	 * 移除回调
	 */
	public removeResponseCall(key:string){
		if(this._callList){
			this._callList.remove(key);
		}
	}
}